<template>
  <div class="question-num-container">
    <span style="margin-left: 10px; margin-top: 5px">各科目题目数量</span>
    <div id="echarts_question_num" style="height: 40vh"></div>
  </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import question from "@/api/question";
import * as echarts from "echarts";
import { useRouter, useRoute } from "vue-router";

// 声明图表实例的引用
let myCharts = null;
// 添加一个变量跟踪当前显示的是哪种数据
const currentView = ref("all"); // 'all' 或 'subject'
const currentSubjectId = ref(null);

// 初始化图表的函数
const initChart = async () => {
  if (!myCharts) {
    myCharts = echarts.init(document.getElementById("echarts_question_num"));
  } else {
    myCharts.clear();
    // 移除之前的事件监听器
    myCharts.off("click");
  }

  let res;
  let option;

  if (currentView.value === "all") {
    // 显示所有科目的统计
    res = await question.statisticsAll();
    option = {
      series: [
        {
          type: "pie",
          data: res.data,
          label: {
            show: true,
            formatter: "{b}: {c}", // 显示名称和数值
          },
        },
      ],
    };

    // 为全局视图添加点击事件，点击后显示单个科目的详情
    myCharts.on("click", function (params) {
      console.log(params.data.id);
      currentSubjectId.value = params.data.id;
      currentView.value = "subject";
      // 重新初始化图表以显示科目详情
      initChart();
    });
  } else {
    // 显示单个科目的详细统计
    res = await question.statisticsBySubjectId(currentSubjectId.value);
    option = {
      // 这里配置科目详情的图表选项
      series: [
        {
          type: "pie", // 或其他适合的图表类型
          data: res.data,
          label: {
            show: true,
            formatter: "{b}: {c}",
          },
        },
      ],
    };

    // 为科目详情视图添加返回按钮事件
    myCharts.on("click", function () {
      // 也可以设置特定区域为返回按钮，而不是整个图表
      currentView.value = "all";
      initChart();
    });
  }

  myCharts.setOption(option);
};

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  if (myCharts) {
    myCharts.dispose(); // 销毁图表实例释放资源
    myCharts = null;
  }
});
</script>

<style scoped>
.question-num-container {
  background-color: white;
}
</style>
